package com.neusoft.jxc.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.neusoft.jxc.bean.SysUser;

/**
 * 
 * @author chens
 *
 */
public class LoginFilter implements Filter {
	private String[] uriArray = new String[] { "/css", "/images", "/js", "/json", "/index.jsp", "/login.jsp",
			"/validatecode.jsp", "/login" };

	@Override
	public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) arg0;
		HttpServletResponse response = (HttpServletResponse) arg1;

		String uri = request.getRequestURI();
		SysUser user = (SysUser) request.getSession().getAttribute("loginUser");
		String contextPath = request.getContextPath();

		// 编写过滤器时可以拦截所有的请求地址，过滤器中做排除操作
		if (user != null || uri.indexOf(contextPath + uriArray[0]) == 0 || uri.indexOf(contextPath + uriArray[1]) == 0
				|| uri.indexOf(contextPath + uriArray[2]) == 0 || uri.indexOf(contextPath + uriArray[3]) == 0
				|| uri.indexOf(contextPath + uriArray[4]) == 0 || uri.indexOf(contextPath + uriArray[5]) == 0
				|| uri.indexOf(contextPath + uriArray[6]) == 0 || uri.indexOf(contextPath + uriArray[7]) == 0) {
			// 会话中保存有用户信息，则用户已经成功登录；可以继续访问其他资源
			arg2.doFilter(request, response);
		} else {
			// 没有检查到登录的用户,则使用服务器端页面跳转技术 ，跳转到登录页面
			// 服务的页面跳转有两种方法：请求转发 和 重定向
			response.sendRedirect(contextPath + "/login.jsp");
		}

	}

	@Override
	public void destroy() {
		
		
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {
		
		
	}

}
